<?php
use think\db\Expression;
use think\Request;
/**
 *  @file : common.php
 *  @brief: 后台公共函数
 */

/**
 *  @brief  : DES加密
 *  @param [in] $text : 欲加密的数据
 *  @param [in] $skey : 密钥
 *  @return : 加密后的字符串
 *  @details: 
 */
function encrypt($text, $skey = 'ZHANGYUANFEI') {
  $piv = substr(strtoupper(md5($skey)), 0, 8);
  $eax = openssl_encrypt($text, 'DES', $piv, OPENSSL_RAW_DATA, $piv);
  $eax = bin2hex($eax);
  $eax = strtoupper($eax);
  return $eax;
}
/**
 *  @brief  : DES解密
 *  @param [in] $text : 欲解密的数据
 *  @param [in] $skey : 密钥
 *  @return : 解密后的字符串
 *  @details: 
 */
function decrypt($text, $skey = 'ZHANGYUANFEI') {
  $buf = hex2bin($text);
  $piv = substr(strtoupper(md5($skey)), 0, 8);
  $eax = openssl_decrypt($buf, 'DES', $piv, OPENSSL_RAW_DATA, $piv);
  return $eax;
}
/**
 *  @brief  : 获取当前数据库中的所有游戏定义
 *  @return : array
 *  @details: 
 */
function GetGameKind() {
  $list = [];
  if (empty($list)) {
    $rows = table('GameKindItem', 'rydb.basic')->select();
    if (!empty($rows)) {
      foreach($rows as $row) {
        $list[$row['KindID']] = $row['GameName'];
      }
    }
  }
  return $list;
}

/**
 * @brief  : 定义当前游戏房间类型
 *  @return : array
 *  @details:
 */
function GetFamilyType(){
    $list[1] = '房卡类型';
    $list[2] = '金币类型';
    return $list;
}

/**
 *  @brief  : 获取当前数据库中的所有代理地区
 *  @return : array
 *  @details: 
 */
function GetAgentType() {
  $list = [];
  $rows = table('AgentType', 'rydb.websms')->order('AgentType')->select();
  if (!empty($rows)) {
    foreach($rows as $row) {
      $list[$row['AgentType']] = $row['AgentTypeName'];
    }
  }
  return $list;
}
/**
 *  @brief  : 获取所有后台角色
 *  @return : array
 *  @details: 
 */
function GetAdminRole() {
  $list = [];
  $rows = $ROLES = table('Ky_AdminRole', 'rydb.websms')->order('ID')->select();
  if (!empty($rows)) {
    foreach($rows as $row) {
      $list[$row['ID']] = $row['Title'];
    }
  }
  return $list;
}
/**
 *  @brief  : 获取当前数据库中的所有渠道
 *  @return : array
 *  @details: 
 */
function GetAllChannel() {
  static $_cache = [];
  if (empty($_cache)) {
    $rows = table('ChannelConfig', 'rydb.basic')->where(['State' => 1])->column('ID,Name');
    $_cache = empty($rows) ? [] : $rows;
  }
  return $_cache;
}

function AddAdminLog($strResult, $strLogType='All') {
  $data = [
    'AdminId' => session(config('auth.session')),
    'LogType' => $strLogType,
    'Result'  => $strResult,
    'AddTime' => new Expression('GETDATE()'),
    'AddIP'   => request()->ip(),
    'Sort'      => 0,
    'IsSys'     => 0,
    'IsDisabled'=> 0,
    'IsDelete'  => 0,
  ];
  table('Ky_AdminLog', 'rydb.websms')->insert($data);
}
/**
 *  @brief  : 通知游戏服务器
 *  @param [in] $page   : 通知页面
 *  @param [in] $params : 传递参数
 *  @param [in] $prefix : 默认为空表示按host适配
 *  @return : array/RuntimeException
 *  @details: 
 */
function CallGameSrv($page,$params, $prefix = '') {
  
  // 确定通知地址, 默认为数据库地址
  // $host = config('rydb. basic', null, $prefix);
  // if (!empty($host)) {
  //   $host = "http://{$host['hostname']}:18000";
  // } else {
  //   $host = $prefix;
  // }
  $host = "http://121.37.249.148:8089";
  $query = empty($params) ? '' : http_build_query($params);
  $page = trim($page, '/');
  $url = "{$host}/{$page}".(empty($query) ? '' : "?{$query}");

  $retn = curl_http([
    CURLOPT_URL     => $url,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_CONNECTTIMEOUT  => 5,
  ]);
  
  $errno = $retn['errno'];
  $error = $retn['error'];
  $http_code  = $retn['info']['http_code'];
  $total_time = $retn['info']['total_time'];
  $data = $retn['data'];
  
  trace([
    'url'         => $url,
    'query'       => $query,
    'errno'       => $errno,
    'error'       => $error,
    'http_code'   => $http_code,
    'total_time'  => $total_time,
    'data'        => $data,
  ]);
  
  if ($errno != 0 || $http_code != 200) {
    $code = $errno > 0 ? $errno : $http_code;
    $message = empty($error) ? $data : $error;
    throw new RuntimeException($message, $code);
  }
  return $data;
}


/**
 *  @brief  : 请求Go服务器
 *  @param [in] $addr   : 端口
 *  @param [in] $params : 传递参数
 *  @param [in] $prefix : 默认为空表示按host适配
 *  @return : array/RuntimeException
 *  @details:
 */
function CallGoSrv($params,$addr) {
    $host = "http://47.96.122.75:{$addr}";
    $query = empty($params) ? '' : http_build_query($params);
    $url = "{$host}/monitor".(empty($query) ? '' : "?{$query}");
    $retn = curl_http([
        CURLOPT_URL     => $url,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT  => 5,
    ]);

    $errno = $retn['errno'];
    $error = $retn['error'];
    $http_code  = $retn['info']['http_code'];
    $total_time = $retn['info']['total_time'];
    $data = $retn['data'];
    trace([
        'url'         => $url,
        'query'       => $query,
        'errno'       => $errno,
        'error'       => $error,
        'http_code'   => $http_code,
        'total_time'  => $total_time,
        'data'        => $data,
    ]);
//    return result(['dd'=>$retn],101,'dd');
    if ($errno != 0 || $http_code != 200) {
        $code = $errno > 0 ? $errno : $http_code;
        $message = empty($error) ? $data : $error;
        throw new RuntimeException($message, $code);
    }

    return $data;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }
    return $result;
}